/*
 * Copyright (C) 2012 Fabio Hufschmid at bfh.ch
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package ch.bfh.aeneas.utils;

import android.content.Context;
import android.content.res.AssetManager;
import android.util.Log;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Copy the assets shipped with the activity to the scard
 * code from http://stackoverflow.com/questions/4447477/android-how-to-copy-files-in-assets-to-sdcard
 * @author Fabio Hufschmid at bfh.ch
 */
public class AssetsHelper {
 
    /**
     * Copy all the assets of the passed context to the sdcard
     * @param ctx 
     */
    public static void copyAssets(Context ctx, String path) {
        
        File folder = new File(path);
        if(!folder.exists()) {
            folder.mkdir();
            folder.setReadable(true,false);
            folder.setWritable(true,false);
        }
        
        AssetManager assetManager = ctx.getAssets();
        try {
            InputStream in;
            OutputStream out;
            File file;
            String[] files = assetManager.list("");
            for(String filename : files) {
                file = new File(path+filename);
                if(!file.exists()) {
                    in = null;
                    out = null;
                    try {
                        in = assetManager.open(filename);
                        out = new FileOutputStream(file);
                        copyFile(in, out);
                        in.close();
                        in = null;
                        out.flush();
                        out.close();
                        out = null;
                    } catch(Exception e) {
                        Log.e("tag", e.getMessage());
                    }
                }
            }
        } catch (IOException e) {
            Log.e("tag", e.getMessage());
        }        
    }
    
    private static void copyFile(InputStream in, OutputStream out) throws IOException {
        byte[] buffer = new byte[1024];
        int read;
        while((read = in.read(buffer)) != -1){
            out.write(buffer, 0, read);
        }
    }
}
